<?php
namespace app\home\controller;

use app\common\model\User as UserModel;
use app\common\controller\HomeBase;
use think\Db;
use think\Config;

/**
 * Index
 * Class Index
 */
class Index extends HomeBase
{
	/**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $menu = 'index';	
        return $this->fetch('index', ['menu' => $menu]);

    }
    /**
     * 分类页
     * @return mixed
     */
    public function category()
    {
    	$menu = 'category';
        return $this->fetch('category', ['menu' => $menu]);
    }
    /**
     * 购物车
     * @return mixed
     */
    public function cart()
    {
    	$menu = 'cart';
        return $this->fetch('cart', ['menu' => $menu]);
    }
    /**
     * 注册
     * @param  int $share_id 推荐人的id
     * @return mixed
     */
    public function reg($share_id = '')
    {
        if (session('uid') > 0) {                       // 是否已经登录
            $this->redirect('Home/User/Index');
        }
        if ($share_id) {                                // 推荐链接获取推荐人的id
            $share_info =  db('user')->where('id',$share_id)->find();
            if ($share_info) {
                session('share_id',$share_id);          // 推荐人保存在session
            }
        }
        if (session('share_id')) {
            $share_name =  db('user')->where('id',session('share_id'))->value('user_name');
            $this->assign('share_name',$share_name); 
        }
        // 获取服务条款
        $server =  db('article')->where('id','4')->value('content');
        $server =  htmlspecialchars_decode($server);
    	$post_url = url('Home/Index/do_reg');			// 注册提交地址
        return $this->fetch('reg', ['post_url' => $post_url,'server' => $server]);
    }
    /**
     * 用户进行注册
     * @return mixed
     */
    public function do_reg()
    {
    	if ($this->request->isPost()) {
            $data = $this->request->post();             // 表单提交的数据
            $validate = validate('DoReg');              // 验证规则
            // 验证数据
            if(!$validate->check($data)){       
                show(0,$validate->getError());          // 验证错误提示
            }else{                                      // 验证成功进行注册
                // 判断发送短信的手机号是否一致
                if ($data['mobile'] !== session('reg_mobile')) {
                    show(0,'手机号码已改变请重新操作！');
                // 验证码判断
                }elseif ((int)$data['mobile_code'] !== session('reg_code')) {
                    show(0,'验证码错误！');
                }
                $data['password']  = md5($data['password'] . Config::get('salt'));
                $data['user_name'] = $data['mobile'];
                if (session('share_id')) {              // 写入推荐人
                    $data['share_id']  = session('share_id');
                    // 查找推荐人已经推荐多少人
                    $amount = db('user')->where("share_id = ".$data['share_id'])->count();
                    // 推荐50人提升日封顶和总封顶
                    if ($amount == '49') {
                        db('user')-> where("id = ".$data['share_id'])->setField('share_level','1');
                    // 推荐100人
                    }elseif($amount == '99'){
                        db('user')-> where("id = ".$data['share_id'])->setField('share_level','2');
                    }
                }
                $user = new UserModel();
                if ($user->allowField(true)->save($data)) {
                    show(1,'注册成功',url('Home/Index/login'));
                } else {
                    show(0,'注册失败');
                }
            }
        }
    }
    /**
     * 登录
     * @return mixed
     */
    public function login()
    {
        if (session('uid') > 0) {                       // 是否已经登录
            $this->redirect('Home/User/Index');
        }
        $post_url = url('Home/Index/do_login');           // 登录提交地址
        return $this->fetch('login', ['post_url' => $post_url]);
    }
    /**
     * 用户进行登录
     * @return mixed
     */
    public function do_login()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();             // 表单提交的数据
            $validate = validate('DoLogin');            // 验证规则
            // 验证数据
            if(!$validate->check($data)){       
                show(0,$validate->getError());          // 验证错误提示
            }else{                                      // 验证成功进行注册
                $password  = md5($data['password'] . Config::get('salt'));
                $user = db('user')->where("mobile",$data['mobile'])->find();
                if ($password !== $user['password']) {
                    show(0,'账户或密码错误');
                }elseif ($user['status'] == '0') {
                    show(0,'该用户被锁定');
                }else{
                    session('uid',$user['id']);
                    show(1,'登录成功',url('Home/User/index'));
                }
            }
        }
    }
    /**
     * 忘记密码
     * @return mixed
     */
    public function forget()
    {
        if (session('uid') > 0) {                       // 是否已经登录
            $this->redirect('Home/User/Index');
        }
        if ($this->request->isPost()) {
            $data = $this->request->post(); 
            $validate = validate('Forget');              // 验证规则
            // 验证数据
            if(!$validate->check($data)){       
                show(0,$validate->getError());          // 验证错误提示
            }else{
                // 判断发送短信的手机号是否一致
                if ($data['mobile'] !== session('forget_mobile')) {
                    show(0,'手机号码已改变请重新操作！');
                // 验证码判断
                }elseif ((int)$data['code'] !== session('forget_code')) {
                    show(0,'验证码错误！');
                }
                $password = md5($data['new_pwd'] . Config::get('salt'));
                $this->user_model = new UserModel();
                $res = $this->user_model->save(['password' => $password],['mobile' => $data['mobile']]);
                // 如果要修改的密码和原始密码相同 sql执行返回false 所以默认执行成功
                show(1,'修改成功',url('Home/Index/login'));
                /*if ($res) {
                    show(1,'修改成功',url('Home/Index/login'));
                }else{
                    show(0,'修改失败');
                }*/
            }
        }
        // 提交地址
        $post_url = url('Home/Index/forget');           
        return $this->fetch('forget', ['post_url' => $post_url]);
    }

    public function errorr()
    {
        return $this->fetch('error');
    }

    /**
     * 注册领红包
     * @return mixed
     */
    public function bonus()
    {
        if (!session('uid')) {                       // 是否已经登录
            show(0,'请登录后操作！',url('Home/index/login'));
        }
        // 获取用户信息
        $user_info = db('user')->where("id = ".session('uid'))->find();
        if ($user_info['is_bonus']) {
            show(0,'你已经领取红包');
        }
        // 获取红包
        //$bonus = rand($this->proConfig['min_bonus']*100,$this->proConfig['max_bonus']*100)/100;
        $bonus = rand($this->proConfig['min_bonus'],$this->proConfig['max_bonus']);
        // 状态改为已经领取红包
        $up_user['is_bonus'] = '1';
        $up_user['re_reg_integral'] = $user_info['re_reg_integral'] + $bonus;
        // 插入记录
        // 会员重消记录
        $log[] =  array(
                        'num'           => $bonus,
                        'wallet_type'   => '2',
                        'change_type'   => '17',
                        'time'          => time(),
                        'uid'           => session('uid'),
                        'before_num'    => $user_info['re_reg_integral'],
                        'later_num'     => $up_user['re_reg_integral'],
                        'description'   => '注册领红包：'.$bonus,
                    );
        model('user')->allowField(true)->save($up_user,['id' => session('uid')]);
        model('fund_log')->saveAll($log);
        show(0,'领取红包'.$bonus,url('Home/user/financeList'));
    }
}
